<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3.着色器实现像素动画-缓动函数与非线性插值</title>
    <style>
        canvas{
            border:1px solid #aaa;
            margin: 0 auto;
            display: block;
        }
    </style>
</head>
<body>
    <canvas width="554" height="554"></canvas>
    <script src="/common/lib/gl-renderer.js"></script>

    <script type="module">
        import { loadImage, toPolar, fromPolar } from "/common/lib/utils.js";
        import {Animator} from '/common/lib/animator.js';
        

        /**
         * gl-renderer五步法
         * 1.创建renderer对象
         * 2.创建并启用webgl程序
         * 3.设置uniform变量
         * 4.将定点数据送入缓冲区
         * 5.渲染
         * 
        */
        // 1.
        let canvas = document.querySelector("canvas");
        const renderer = new GlRenderer(canvas);

        // 2.
        const vertex = `
            attribute vec2 a_vertexPosition;
            attribute vec2 uv;
            varying vec2 vUv;

            uniform vec2 translation;

            void main(){
                gl_PointSize = 1.0;
                vUv = uv;
                mat3 transformMatrix = mat3(
                    1, 0, 0,
                    0, 1, 0,
                    translation, 1
                );
                vec3 pos = transformMatrix * vec3(a_vertexPosition, 1.0);
                gl_Position = vec4(pos, 1.0);
            }
        `
        // 
        const fragment = `
            #ifdef GL_ES
            precision highp float;
            #endif

            void main() {
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
            }
        `
        const program = renderer.compileSync(fragment, vertex);
        renderer.useProgram(program);

        const textureURL = 'https://p.ssl.qhimg.com/t01f265b6b6479fffc4.png';
        const texture = await renderer.loadTexture(textureURL);

        renderer.uniforms.translation = [0.0, 0.0];
        
        renderer.setMeshData([{
            positions: [
                [-0.8, -0.05],
                [-0.8, 0.05],
                [-0.7, 0.05],
                [-0.7, -0.05],
            ],
            attributes: {
                uv: [
                    [0, 0],
                    [0, 1],
                    [1, 1],
                    [1, 0],
                ],
            },
            cells: [[0, 1, 2], [2, 0, 3]],
        }]);
        renderer.render();

        // p = p ** 2; // 匀加速运动
        // p = p * (2 - p); // 匀减速运动
        // p * p * (3.0 - 2.0 * p); // smoothstep效果
        const animator = new Animator({duration: 2000, easing: p => p * (2 - p)});
        animator.animate(renderer, ({target, timing}) => {
            target.uniforms.translation = [-0.5 * (1 - timing.p) + 0.5 * timing.p, 0];
        });

    </script>
</body>
</html>